package com.atguigu.tingshu.album.config.rabbit;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Haoran Sun
 * @since 2024/08/18
 */

@Component
@Slf4j
public class ReturnAndConfirmConfig {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //confirm模式
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack){
                log.info("消息发送成功");
            }else{
                log.error("消息发送失败:{}",cause);
            }
        });
        // return模式
        rabbitTemplate.setReturnsCallback((returnedMessage) -> {
            Message message = returnedMessage.getMessage();
            String exchange = returnedMessage.getExchange();
            String routingKey = returnedMessage.getRoutingKey();
            int replyCode = returnedMessage.getReplyCode();
            String replyText = returnedMessage.getReplyText();
            String msg = new String(message.getBody());
            log.error("消息未抵达消息队列,消息交换机为：{}，消息routingKey为：{}，消息错误码为：{}，消息错误原因为：{}，消息内容为：{}",
                    exchange,routingKey,replyCode,replyText,msg);
        });


    }

}
